import {makeid} from '../../utils'

Vue.component('comb-input', {
  template:
    `
<div style="display: flex">
  <input :list="getName('flavors')" 
         :id="getName('choice')"
         v-model="str"
    @change="handleChange"
  />
  <datalist :id="getName('flavors')">
    <option
        v-for="item in getOptions(str)"
        :key="item.value"
        :label="item.label"
        :value="item.value">
    </option>
  </datalist>
</div>
` ,
  props: {
    value: null,
    list: Array
  },
  data() {
    return {
      id: "ice-cream-" + makeid(10),
      str: this.value,
      options: this.list.map(v => {
        return {
          label: v,
          value: v
        }
      })
    }
  },
  methods: {
    handleChange($event) {
      this.fireCom($event.target.value)
    },
    getValue(value) {
      return value
    },
    fireCom(value) {
      this.$emit('change', this.getValue( value ))
    },
    reset() {
      this.str = ''
    },
    getName(v) {
      return this.id + '-' + v
    },
    getOptions(str) {
      let _v  = str.trim()
      if (!_v) {
        return []
      }
      // console.log(this.options)
      return this.options.filter(v => {
        return v.label.startsWith(str)
      })
    }
  },
})

Vue.component('comb-demo', {
  template:
    `
<div>
  <h3>普通选择</h3>
  <div>{{model}}</div>
  <div>{{parsedModel}}</div>
  <comb-input :value="model.position"
               :list="['fixed', 'absolute', 'relative']"
               @change="onFormChange('position', $event)"></comb-input>
</div>
`,
  data() {
    return {
      model: {
        position: ''
      },
      parsedModel: {}
    }
  },
  methods: {
    onFormChange(key, e) {
      // console.log(key, e)
      this.$nextTick(() => {
        this.$set(this.parsedModel, key, e)
      })
    }
  },
})
